import os

from fastapi import FastAPI
from tortoise.contrib.fastapi import RegisterTortoise

TORTOISE_MODELS = ["model.base"]
# -----------------------数据库配置-----------------------------------
DB_ORM_CONFIG = {
    # Tortoise可以连接多个数据库
    "connections": {
        # 字典格式的连接配置文件
        'default': {
            'engine': 'tortoise.backends.mysql',  # 要连接数据库类型
            "credentials": {
                'host': os.getenv('MYSQL_HOST', '127.0.0.1'),
                'user': os.getenv('MYSQL_USERNAME', 'root'),
                'password': os.getenv('MYSQL_PASSWORD', 'root'),
                'port': os.getenv('MYSQL_PORT', 3306),
                'database': os.getenv('MYSQL_DATABASE', 'myapp'),
            }
        }

    },

    'apps': {
        'base': {
            'models': TORTOISE_MODELS,
            'default_connection': 'default'
        }
    },
    "use_tz": False,
    'timezone': 'Asia/Shanghai'
}


async def register_mysql(app: FastAPI):
    # 注册数据库
    await RegisterTortoise(
        app,
        config=DB_ORM_CONFIG,
        generate_schemas=True,
        add_exception_handlers=False,
    )
    print("数据库连接成功")

# 异步上下文管理器
# async def register_mysql(app: FastAPI):
#     try:
#         async with RegisterTortoise(
#                 app,
#                 config=DB_ORM_CONFIG,  # 传入配置，连接数据库
#                 generate_schemas=True  # 是否在建立连接时根据模型建立数据表
#         ):
#             yield print("Mysql数据库连接成功")
#             await connections.close_all()
#             print("数据库连接已经关啦")
#     except Exception as e:
#         print(e)